<template>
  <el-dialog
    :title="rowData.id ? '编辑采购信息' : '添加采购信息'"
    :visible.sync="dialogVisible"
    :show="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :before-close="handleClose"
    width="800px"
    @open="open"
    destroy-on-close
  >
    <el-form
      ref="form"
      v-loading="infoLoading"
      :model="info"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="信息类型" prop="type">
            <el-select v-model="info.type" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="parseInt(info.type) === 2"
            label="省/市"
            prop="address"
          >
            <el-cascader
              placeholder="请选择省市"
              v-model="info.address"
              :options="cityMapOptions"
              :props="{ value: 'label' }"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="需求标题" prop="title">
            <el-input
              type="textarea"
              v-model="info.title"
              placeholder="请输入需求标题"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="产品图片" prop="image">
            <el-upload
              list-type="picture-card"
              :action="uploadAction"
              :on-change="imgPreview"
              accept=".jpeg,.png,.jpg"
              :limit="6"
              :on-exceed="handleExceed"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="onSuccess"
              :file-list="fileList"
            >
              <i class="el-icon-plus"></i>
              <template #tip>
                <div class="el-upload__tip">
                  提示：只允许上传.jpg,.jpeg,.png格式图片, 且大小不超过2M,
                  最多支持上传6张
                </div>
              </template>
            </el-upload>
            <el-dialog
              title="预览图片"
              :visible.sync="dialogVisible_pic"
              :close-on-click-modal="false"
              :close-on-press-escape="false"
              append-to-body
            >
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="需求详情" prop="details">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4 }"
              v-model="info.details"
              style="width: 660px"
              placeholder="请输入需求详情"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="12">
          <el-form-item label="国家" prop="country">
            <el-input v-model="info.country" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国旗" prop="countryFlag">
            <el-input v-model="info.countryFlag" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="需求数量" prop="requireQuantity">
            <el-input type="text" v-model="info.requireQuantity" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parseInt(info.type) === 1">
          <el-form-item label="目标价格" prop="targetPrice">
            <el-input
              type="text"
              v-model="info.targetPrice"
              placeholder="请输入目标价格"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parseInt(info.type) === 2">
          <el-form-item label="需求金额" prop="requireAmount">
            <el-input
              type="text"
              v-model="info.requireAmount"
              placeholder="请输入需求金额"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="24">
          <el-form-item label="采购标签" prop="categoryStub">
            <el-input
              type="text"
              v-model="info.categoryStub"
              placeholder="当有多个采购标签时,请用“|”进行分隔"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="12">
          <el-form-item label="目的地" prop="destination">
            <el-input type="text" v-model="info.destination" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商区域" prop="supplierArea">
            <el-input type="text" v-model="info.supplierArea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="12">
          <el-form-item label="付款方式" prop="paymentTerms">
            <el-input type="text" v-model="info.paymentTerms" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发运方式" prop="shippingTerms">
            <el-input type="text" v-model="info.shippingTerms" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 2">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contacts">
            <el-input type="text" v-model="info.contacts" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="mailbox">
            <el-input type="text" v-model="info.mailbox" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 2">
        <el-col :span="12">
          <el-form-item label="微信" prop="wechat">
            <el-input type="text" v-model="info.wechat" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input type="text" v-model="info.phone" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发布时间" prop="releaseTime">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="info.releaseTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到期时间" prop="expireTime">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="info.expireTime"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3 }"
              v-model="info.remark"
              style="width: 660px"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button :disabled="infoLoading" type="primary" @click="subInfo"
            >确 定</el-button
          >
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">取 消</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import { postAction } from "@/api/common";
import cityMap from "./chinaMap.json";

export default {
  name: "edit",
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      // 对象或数组默认值必须从一个工厂函数获取
      default: function () {
        return false;
      },
    },
  },
  data() {
    return {
      fileList: [],
      dialogImageUrl: "",
      dialogVisible_pic: false,
      uploadAction: "/api/Upload/UploadBuyerDataImg",
      dialogVisible: this.show,
      isChange: false,
      initForm: true,
      cityMapOptions: cityMap,
      typeOptions: [
        {
          value: 1,
          label: "全球采购商",
        },
        {
          value: 2,
          label: "国内采购商",
        },
      ],
      // 页面元素
      info: {
        files: "",
        image: [],
      },
      infoLoading: true,
      // 验证
      rules: {
        title: [
          { required: true, message: "需求标题不能为空", trigger: "change" },
        ],
        details: [
          { required: true, message: "详细描述不能为空", trigger: "change" },
        ],
        country: [
          { required: true, message: "国家不能为空", trigger: "change" },
        ],
        targetPrice: [
          { required: true, message: "目标价格不能为空", trigger: "change" },
        ],
        destination: [
          { required: true, message: "目的地不能为空", trigger: "change" },
        ],
        supplierArea: [
          { required: true, message: "供应商区域不能为空", trigger: "change" },
        ],
        paymentTerms: [
          { required: true, message: "付款方式不能为空", trigger: "change" },
        ],
        shippingTerms: [
          { required: true, message: "发运方式不能为空", trigger: "change" },
        ],
        releaseTime: [
          { required: true, message: "发布时间不能为空", trigger: "change" },
        ],
        expireTime: [
          { required: true, message: "到期时间不能为空", trigger: "change" },
        ],
        address: [
          { required: true, message: "省/市不能为空", trigger: "change" },
        ],
      },
    };
  },

  watch: {
    show() {
      this.dialogVisible = this.show;
      this.initForm = true;
    },
    info: {
      handler: function () {
        if (this.initForm) {
          this.isChange = false;
          this.initForm = false;
        } else {
          this.isChange = true;
        }
      },
      deep: true,
    },
  },
  methods: {
    async open() {
      this.infoLoading = true;
      // eslint-disable-next-line eqeqeq
      if (this.rowData.id) {
        this.info = this.rowData;
        if(this.rowData.address){
          this.info.address = this.rowData.address.split("-");
        }
        console.log("this.rowData.image:" + this.rowData.image);
        this.fileList = this.rowData.image;
      } else {
        this.fileList = [];
        this.info = {
          type: 1,
        };
      }
      this.infoLoading = false;
    },
    // 添加图片
    imgPreview(file, fileList) {
      this.infoLoading = true;
      const isType =
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/jpg" ||
        file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isType) {
        // 移除最后一个元素
        fileList.pop();
        this.$message.error("上传图片只能是 JPG,JPEG,PNG 格式!");
        this.infoLoading = false;
      }
      if (!isLt2M) {
        // 移除最后一个元素
        fileList.pop();
        this.$message.error("上传图片大小不能超过 2MB!");
        this.infoLoading = false;
      }
      this.infoLoading = false;
    },

    // 上传图片
    onSuccess(res, file, fileList) {
      console.table(res);
      console.table(file);
      console.table(fileList);

      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.fileList.push({ name: file.name, url: res.data });
      console.table(this.info.image);
    },
    handleRemove(file, fileList) {
      console.log(file.uid);
      let Pics = this.info.image;
      Pics.forEach((item, index) => {
        if (file.uid == item.uid) {
          Pics.splice(index, 1);
        }
      });
    },
    // 提交表单
    subInfo() {
      this.$refs.form.validate(async (valid) => {
        // form验证
        if (valid) {
          let res;
          console.log("this.fileList:" + this.fileList);
          console.log("tt:" + JSON.stringify(this.fileList));
          this.info.image = JSON.stringify(this.fileList);
          if(this.info.type === 2){
            this.info.address = this.info.address[0]+"-"+this.info.address[1];
          }
          if (this.info.id) {
            res = await postAction(this.info, "buyerData/Edit");
          } else {
            res = await postAction(this.info, "buyerData/Add");
          }
          //this.$message.success('提交成功')
          if (res.code === 20000) {
            this.$message({
              type: "success",
              message: res.message,
              center: true,
            });
          } else {
            this.$message({
              type: "warning",
              message: res.message,
              center: true,
            });
          }
          this.infoLoading = false;
          // 调用父级页面方法
          this.closeAction();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible_pic = true;
    },
    // 上传图片个数限制
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm("您有未保存的修改，确定关闭此页吗？", "提示", {
          type: "warning",
        })
          .then((_) => {
            this.$emit("update:show", false);
            this.reset();
          })
          .catch((_) => {});
      } else {
        this.reset();
        this.$emit("update:show", false);
      }
    },
    closeAction() {
      this.$emit("closeAction");
    },
    reset() {
      this.info = {};
    },
  },
};
</script>

<style scoped>
</style>
